﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Reflection;
using NPOI.SS.UserModel;

namespace Common.Utilities.Excel.Export
{
    public class CellStyle : CellStyleBase
    {
        /// <summary>
        /// 单元格格式
        /// </summary>
        public ICellStyle Style { get; set; }

        public ExcelExportProvider ExcelExportProvider { get; set; }

        /// <summary>
        /// 此样式的字体
        /// </summary>
        public Font Font { get; set; }

        public DataFormat DataFormat { get; set; }

        public CellStyle(XmlNode cellStyleNode, ExcelExportProvider excelExportProvider)
            : base(cellStyleNode)
        {
            XmlNode XNode = cellStyleNode.SelectSingleNode("Font");
            if (XNode != null)
                Font = new Font(XNode, this);
            XNode = cellStyleNode.SelectSingleNode("DataFormat");
            if (XNode != null)
                DataFormat = new DataFormat(XNode, this);
            this.ExcelExportProvider = excelExportProvider;
        }

        //private List<Font> GetFonts(XmlNode cellStyleNode)
        //{
        //    List<Font> fonts = new List<Font>();
        //    XmlNodeList xNodes = cellStyleNode.SelectNodes("Font");
        //    if (xNodes != null && xNodes.Count > 0)
        //    {
        //        foreach (XmlNode xNode in xNodes)
        //        {
        //            Font font = new Font(xNode, this);
        //            fonts.Add(font);
        //        }
        //    }
        //    return fonts;
        //}

        /// <summary>
        /// 设置单元格的一级格式(一级格式即可以直接用CellStyle.Property来赋最终值的)
        /// </summary>
        public void SetCellStyle(ICell cell, IWorkbook workbook)
        {
            if (Style == null)
            {
                Style = workbook.CreateCellStyle();
                if (Properties.Count != 0)
                {
                    Type cellType = Style.GetType();
                    // 用反射为cellType对象的每一个有配置到的属性赋值
                    for (int iLoop = 0; iLoop < Properties.Count; iLoop++)
                    {
                        PropertyInfo property = cellType.GetProperty(Properties[iLoop]);
                        object value = Arguments[iLoop].GetValue();
                        property.SetValue(Style, value, null);
                    }
                }
                if(Font != null)
                    Font.SetCellFont(workbook);
                if (DataFormat != null)
                    DataFormat.SetDataFormat(workbook);
            }
            cell.CellStyle = Style;
        }
    }
}
